import Models,Commands
from Parser import *
from sys import exit
import RoomMaker
"""The game can be in various states, these basically factor out MOTD/login/character creation/

   This is all a bit crap and unreadable, should really sort this out, there is a lot of smelly object usage here

   like self.game.gamestate.go()
"""

import Gamestates

class Gamestate:
   def __init__(self,game):
      self.game = game
   def transfer(self,statename):
      try:
         state = getattr(Gamestates,statename)
      except:
         """This doesn't exit the program properly"""
         print "State not defined"
         exit()
      self.game.gamestate = state(self.game)
      self.game.gamestate.go()

class MOTD(Gamestate):
   def go(self):
      try:
         f = open("motd","r")
         for line in f.readlines():
            self.game.write(line)
      except:
         self.game.write("MOTD file not found\n")
      self.transfer("Playername")

class Playername(Gamestate):
   def go(self):
      self.game.write("Player name:")
   def input(self,data):
      """Validate the name against the names in the db"""
      name = data.strip().lower()
      try:
         player = Models.Player.select(Models.Player.q.name==name)[0]
         setattr(self.game,"player",player)
         self.transfer("Gameloop")
      except:
         """Should of course go to player creation"""   
         self.game.write("Not in db\n")
         self.go()
   
class Gameloop(Gamestate):
   def go(self):
      self.game.write(">>")
   def input(self,data):
      """Validate the game data and dispatch"""
      command,parsedict = dispatch(data)
      print parsedict
      for message in command(player=self.game.player,identifier=parsedict):
         self.game.write(message)
      self.go()
